import { defineStore } from 'pinia'
import { createWs } from '@/comm/ws.js'
import { searchTcApi } from '@/api/search-api'

const arrangeArr = (arr) => {
  let names = ['node']
  let nodes = []
  let nodeset = {}
  for(let oneTm of arr) {
    let tmName = oneTm['name']
    let nodeObj = {'node': tmName}
    for(let oneNode of oneTm['rows']) {
      let timestamp = oneNode['timestamp']
      nodeObj = {...nodeObj, ...{ [timestamp] : oneNode['valuedb'] } }
    }
    nodes.push(nodeObj)
    names.push(tmName)
  }
  nodeset['dimensions'] = names
  nodeset['source'] = nodes
  return nodeset
}

export const useTmStore = defineStore('tm', {
  state: () => {
    return {
      wsObj: null,
      tmArr: [],
      navArr: [],
      hisTmSet: {},
      searchForm: {},
      edUdTmObj: {},
      treeMaxHeight: '600px'
    }
  },
  actions: {

    setSearchForm (obj) {
      this.searchForm = Object.assign({}, obj)
    },
    searchTm (reqJson) {
      searchTcApi(reqJson, (response) => {
        let resData = response.data
        const resTms = resData.data?.tms
        let { dimensions, source } = arrangeArr(resTms)
        this.hisTmSet = { dimensions, source }
      }, (error) => {
        console.log("error:", error)
      })
    },

    setEdUdObj (obj) {
      this.edUdTmObj = Object.assign({}, obj)
    }
  }
})